/*
 * Copyright 2008, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.magneato.aop;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

/**
 * Helper class for AOP logging
 *
 * @author David George
 */
public class LogInterceptor implements MethodBeforeAdvice,
		AfterReturningAdvice, ThrowsAdvice {
	private static Log log = null;

	public LogInterceptor() {
	}

	public void before(Method arg0, Object[] arg1, Object arg2)
			throws Throwable {
		log = LogFactory.getLog(arg2.getClass());
		log.info("Beginning method: " + arg0.getName());
	}

	public void afterReturning(Object arg0, Method arg1, Object[] arg2,
			Object arg3) throws Throwable {
		log = LogFactory.getLog(arg3.getClass());
		log.info("Ending method: " + arg1.getName());
	}

	public void afterThrowing(Method m, Object[] args, Object target,
			Throwable ex) {
		log = LogFactory.getLog(target.getClass());
		log.info("Exception in method: " + m.getName() + " Exception is: "
				+ ex.getMessage());
	}

	/**
	 * Called before and after an injected method.
	 * @param call
	 * @return
	 * @throws Throwable
	 */
	public Object log(ProceedingJoinPoint call) throws Throwable {
		// log = LogFactory.getLog(call.getClass());
		// System.out.println("entering method [" + call.toShortString()
		// +"] with param:" + call.getArgs()[0] );

		Object[] args = call.getArgs();

		System.out.print("entering method [" + call.toShortString() + "]( ");
		for (Object o : args) {  // d gets successively each value in ar.
		    System.out.print(o + " ");
		}
		System.out.println(')');
		Object point = call.proceed();

		System.out.println("exiting method [" + call.toShortString()
				+ "with return as:" + point);


		return point;
	}
}
